import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Card,
  Divider,
  Typography,
  Space,
  Tabs,
  Badge,
  message,
  InputNumber,
  Upload,
  Select,
  TreeSelect,
} from 'antd';
import {
  ExclamationCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  AuditOutlined,
  UploadOutlined,
} from '@ant-design/icons';

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;
import area from '@/components/staticFile/region_options.json';
import condition from '@/components/staticFile/treeSelect.json';
import { page } from '@/services/apis/serviceProviderRegister';
import ProductAllInfosPage from '../ProductManager/productInfos';
import { useModel } from '@umijs/max';
import CompanyAllInfosPage from '../CompanyManager/modal';
import { getProgramRecord, pageRecord, pageUsers } from '@/services/apis/companyRegister';
import dayjs from 'dayjs';
import RecordAllInfosPage from '../RecordManager/modal';
import AcceptanceManagerPage from '../AcceptanceManager/modal';

// 测试数据 - 项目验收管理
const ENTERPRISE_ACCEPTANCE_LIST = [
  {
    id: 'acc001',
    serialNumber: 1,
    enterpriseName: 'ABC制造有限公司',
    digitalLevel: 'Level 3',
    subsidyAmount: 150,
    link: '项目验收',
    status: '待审核',
  },
  {
    id: 'acc002',
    serialNumber: 2,
    enterpriseName: 'DEF科技发展有限公司',
    digitalLevel: 'Level 2',
    subsidyAmount: 60,
    link: '项目验收',
    status: '待审核',
  },
];
const getDigitalLevelText = (level: string) => {
  const levelMap: Record<string, string> = {
    level1: '一级',
    level2: '二级',
    level3: '三级',
    level4: '四级',
    level5: '五级',
  };
  return levelMap[level] || level;
};

const MyTodoPage: React.FC = () => {
  // 状态管理
  const { initialState, setInitialState } = useModel('@@initialState');
  const [activeTab, setActiveTab] = useState(initialState?.currentUser.data.userType == "county" ? "reg": 'product');
  const [productList, setProductList] = useState([]);
  const [enterpriseRegList, setEnterpriseRegList] = useState([]);
  const [enterpriseRecordList, setEnterpriseRecordList] = useState([]);
  // const [programChekcRecordList, setProgramChekcRecordList] = useState([]);
  const [enterpriseAcceptanceList, setEnterpriseAcceptanceList] = useState(
    [],
  );
  const {
    modalProps,
    setModalProps,
  } = useModel("ProductManager.modal")
  const {
    modalProps: companyModalProps,
    setModalProps: setCompanyModalProps,
  } = useModel("CompanyManager.modal")
  const {
    modalProps: recordModalProps,
    setModalProps: setRecordModalProps,
  } = useModel("RecordManager.modal")
  const {
    modalProps: companyCheckProps,
    setModalProps: setCompanyCheckProps,
  } = useModel("AcceptanceManager.modal")
  const [pagination, setPagination] = useState<{ current: number, pageSize: number, total: number }>({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const [comPagination, setComPagination] = useState<{ current: number, pageSize: number, total: number }>({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const [programPagination, setProgramPagination] = useState<{ current: number, pageSize: number, total: number }>({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const [programCheckPagination, setProgramCheckPagination] = useState<{ current: number, pageSize: number, total: number }>({
    current: 1,
    pageSize: 10,
    total: 0
  })
  // 弹窗状态管理
  const [modalState, setModalState] = useState({
    visible: false,
    type: '', // product, reg, record, acceptance
    id: '',
    data: {} as any,
  });

  // 表单管理
  const [reviewForm] = Form.useForm();

  // 打开审核弹窗
  const handleReviewClick = (type: string, record: any) => {
    let data = {};

    // 根据类型获取对应数据
    switch (type) {
      case 'product':
        setModalProps(prev => ({ ...prev, visible: true, record, title: "审核产品" }))
        break;
      case 'reg':
        setCompanyModalProps(prev => ({ ...prev, visible: true, record, title: "企业审核" }))
        break;
      case 'record':
         record.scenesData.forEach((item: any) => {
      record[item["label"]] = item.scenes
    })
        setRecordModalProps(prev => ({ ...prev, visible: true, record, title: "项目备案审核" }))
        // data = getEnterpriseRecordDetail(record.id);
        break;
      case 'acceptance':
        setCompanyCheckProps(prev => ({ ...prev, visible: true, record, title: "审核项目验收管理" }))
        // data = getEnterpriseAcceptanceDetail(record.id);
        break;
      default:
        break;
    }
  };

  // 关闭弹窗
  const handleModalClose = () => {
    setModalState({
      ...modalState,
      visible: false,
    });
  };

  // 提交审核结果
  const handleSubmitReview = async (reviewResult: 'pass' | 'reject' | 'return') => {
    // 校验审核意见
    const validateResult = await reviewForm.validateFields(['reviewOpinion']);
    if (!validateResult) return;

    // 模拟接口请求
    message.loading(
      `正在提交${reviewResult === 'pass' ? '通过' : reviewResult === 'reject' ? '不通过' : '退回'
      }操作`,
    );

    setTimeout(() => {
      // 根据类型更新对应列表
      switch (modalState.type) {
        case 'product':
          // setProductList(productList.filter((item) => item.id !== modalState.id));
          break;
        case 'reg':
          // setEnterpriseRegList(enterpriseRegList.filter((item) => item.id !== modalState.id));
          break;
        case 'record':
          // setEnterpriseRecordList(enterpriseRecordList.filter((item) => item.id !== modalState.id));
          break;
        case 'acceptance':
          // setEnterpriseAcceptanceList(
          //   enterpriseAcceptanceList.filter((item) => item.id !== modalState.id),
          // );
          break;
        default:
          break;
      }
      handleModalClose();
    }, 800);
  };

  // 1. 产品和解决方案管理列配置
  const productColumns = [
    {
      title: '序号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
      width: 100,
      align: 'center',
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
      width: 200,
    },
    {
      title: '服务商名称',
      dataIndex: 'supplierName',
      key: 'supplierName',
      width: 200,
    },
    {
      title: '产品简介',
      dataIndex: 'productEvaluation',
      key: 'productEvaluation',
      width: 120,
      ellipsis: true
    },
    {
      title: '环节',
      dataIndex: 'link',
      key: 'link',
      width: 120,
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'resultStatus',
      key: 'resultStatus',
      width: 120,
      align: 'center',
      // render: (text: string) => <Badge status="processing" text={getStatusText(text)} />,
    },
    {
      title: '操作',
      key: 'operation',
      width: 120,
      align: 'center',
      render: (_: any, record: any) => (
        <Button
          icon={<AuditOutlined />}
          disabled={(() => {
              if (initialState?.currentUser.data.userType == "county") {
                return record.resultStatus != "待县（市、区）经商局审核"
              }
              if (initialState?.currentUser.data.userType == "city") {
                return record.resultStatus != "待市经信局审核"
              }
              return false
            })()}
          type="primary"
          size="small"
          onClick={() => handleReviewClick('product', record)}
        >
          审核
        </Button>
      ),
    },
  ];

  // 2. 试点企业注册管理列配置
  const enterpriseRegColumns = [
    {
      title: '序号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
      width: 80,
      align: 'center',
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '企业名称',
      dataIndex: 'companyName',
      key: 'companyName',
      width: 200,
    },
    {
      title: '联系人',
      dataIndex: 'concatPerson',
      key: 'concatPerson',
      width: 120,
    },
    {
      title: '联系电话',
      dataIndex: 'concatPhone',
      key: 'concatPhone',
      width: 150,
    },
    {
      title: '环节',
      dataIndex: 'link',
      key: 'link',
      width: 120,
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'resultStatus',
      key: 'resultStatus',
      width: 120,
      align: 'center',
      // render: (text: string) => <Badge status="processing" text={getStatusText(text)} />,
    },
    {
      title: '操作',
      key: 'operation',
      width: 120,
      align: 'center',
      render: (_: any, record: any) => (
        <Button
          icon={<AuditOutlined />}
          disabled={(() => {
              if (initialState?.currentUser.data.userType == "county") {
                return record.resultStatus != "待县（市、区）经商局审核"
              }
              if (initialState?.currentUser.data.userType == "city") {
                return record.resultStatus != "待市经信局审核"
              }
              return false
            })()}
          type="primary"
          size="small"
          onClick={() => handleReviewClick('reg', record)}
        >
          审核
        </Button>
      ),
    },
  ];

  // 3. 项目备案管理列配置
  const enterpriseRecordColumns = [
    {
      title: '序号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
      width: "10%",
      align: 'center',
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '企业名称',
      dataIndex: 'companyName',
      key: 'companyName',
      width: "15%",
      ellipsis: true,
    },
    {
      title: '产品和解决方案名称',
      dataIndex: 'productSolutionNames',
      key: 'productSolutionNames',
      width: "15%",
      ellipsis: true,
    },
    {
      title: '关联服务商',
      dataIndex: 'relatedServiceProviders',
      key: 'relatedServiceProviders',
      width: "15%",
      ellipsis: true,
    },
    {
      title: '环节',
      dataIndex: 'link',
      key: 'link',
      width: "10%",
      align: 'center',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'resultStatus',
      key: 'resultStatus',
      width: "10%",
      align: 'center',
      // render: (text: string) => <Badge status="processing" text={getStatusText(text)} />,
    },
    {
      title: '操作',
      key: 'operation',
      width: "10%",
      align: 'center',
      render: (_: any, record: any) => (
        <Button
          disabled={(() => {
              if (initialState?.currentUser.data.userType == "county") {
                return record.resultStatus != "待县（市、区）经商局审核"
              }
              if (initialState?.currentUser.data.userType == "city") {
                return record.resultStatus != "待市经信局审核"
              }
              return false
            })()}
          icon={<AuditOutlined />}
          type="primary"
          size="small"
          onClick={() => handleReviewClick('record', record)}
        >
          审核
        </Button>
      ),
    },
  ];

  // 4. 项目验收管理列配置
  const enterpriseAcceptanceColumns = [
    {
      title: '序号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
      width: 80,
      align: 'center',
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '企业名称',
      dataIndex: 'companyName',
      key: 'companyName',
      width: 200,
    },
    {
      title: '数字化水平等级',
      dataIndex: 'digitalLevel',
      key: 'digitalLevel',
      width: 150,
      render: (level: string) => getDigitalLevelText(level),
    },
    // {
    //   title: '拟对企业奖补资金总额（万元）',
    //   dataIndex: 'subsidyAmount',
    //   key: 'subsidyAmount',
    //   width: 200,
    // },
    {
      title: '环节',
      dataIndex: 'link',
      key: 'link',
      width: 120,
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'resultStatus',
      key: 'resultStatus',
      width: 120,
      align: 'center',
      // render: () => <Badge status="processing" text="待审核" />,
    },
    {
      title: '操作',
      key: 'operation',
      width: 120,
      align: 'center',
      render: (_: any, record: any) => (
        <Button
          disabled={(() => {
              if (initialState?.currentUser.data.userType == "county") {
                return record.resultStatus != "待县（市、区）经商局审核"
              }
              if (initialState?.currentUser.data.userType == "city") {
                return record.resultStatus != "待市经信局审核"
              }
              return false
            })()}
          icon={<AuditOutlined />}
          type="primary"
          size="small"
          onClick={() => handleReviewClick('acceptance', record)}
        >
          审核
        </Button>
      ),
    },
  ];
  const convertNode = (node: any) => ({
    title: node.title,
    value: node.value,
    disabled: node.children && node.children.length > 0, // 非叶子节点禁用
    children: node.children?.map(convertNode),
  });
  // 渲染审核弹窗内容
  const renderModalContent = () => {
    switch (modalState.type) {
      case 'product':
        return (
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            {/* 基本信息 */}
            <Card title="基本信息" bordered>
              <Form layout="vertical" initialValues={modalState.data.basicInfo}>
                <Form.Item
                  label="产品名称"
                  name="productName"
                  rules={[{ required: true, message: '请输入产品名称' }]}
                >
                  <Input placeholder="请输入产品名称" />
                </Form.Item>
                <Form.Item
                  label="所属城市"
                  name="city"
                  rules={[{ required: true, message: '请选择所在城市' }]}
                >
                  <TreeSelect
                    allowClear
                    placeholder="请选择注册城市"
                    treeData={area}
                  // style={COMMON_FIELD_STYLE}
                  />
                </Form.Item>
                <Form.Item
                  label="购买方式"
                  name="purchaseWay"
                  rules={[{ required: true, message: '请选择购买方式' }]}
                >
                  <Select
                    allowClear
                    placeholder="请选择购买方式"
                    options={[
                      { value: 'online', label: '线上' },
                      { value: 'deadline', label: '线下' },
                    ]}
                  />
                </Form.Item>
                <Form.Item
                  label="部署架构"
                  name="deploymentArchitecture"
                  rules={[{ required: true, message: '请选择部署架构' }]}
                >
                  <Select
                    allowClear
                    placeholder="请选择部署架构"
                    options={[
                      { value: 'CS', label: 'CS' },
                      { value: 'BS', label: 'BS' },
                    ]}
                  />
                </Form.Item>
                <Form.Item
                  label="报价区间"
                  name="price"
                  rules={[{ required: true, message: '请输入报价区间' }]}
                >
                  <Space>
                    <Form.Item
                      noStyle
                      name="priceHigh"
                      rules={[{ required: true, message: '请输入报价区间最小值' }]}
                    >
                      <Input placeholder="报价区间最小值" />
                    </Form.Item>
                    ——
                    <Form.Item
                      noStyle
                      name="priceLow"
                      rules={[{ required: true, message: '请输入报价区间最大值' }]}
                    >
                      <Input placeholder="报价区间最大值" />
                    </Form.Item>
                  </Space>
                </Form.Item>

                <Form.Item
                  label="产品展示主视觉"
                  name="productShow"
                  rules={[{ required: true, message: 'Please input your username!' }]}
                >
                  <img
                    src="/images/backgroundbig.png"
                    alt="产品图片"
                    style={{
                      width: '120px',
                      height: '80px',
                      objectFit: 'cover',
                      borderRadius: 4,
                    }}
                  />
                  {/* <Upload>
                    <Button icon={<UploadOutlined />}>点击上传</Button>
                  </Upload> */}
                  {/* <Dragger {...props}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">点击或拖拽上传</p>
          </Dragger> */}
                </Form.Item>
                <Form.Item
                  label="其他资料"
                  name="otherInfo"
                  rules={[{ required: true, message: 'Please input your username!' }]}
                >
                  {/* <Upload>
                    <Button icon={<UploadOutlined />}>上传附件，不大于5M</Button>
                  </Upload> */}
                  <img
                    src="/images/backgroundbig.png"
                    alt="产品图片"
                    style={{
                      width: '120px',
                      height: '80px',
                      objectFit: 'cover',
                      borderRadius: 4,
                    }}
                  />
                </Form.Item>
              </Form>
            </Card>

            {/* 产品描述 */}
            <Card title="产品描述" bordered>
              <Form layout="vertical" initialValues={modalState.data.productDesc}>
                <Form.Item
                  name="productEvaluation"
                  label="产品简介"
                  rules={[{ required: true, message: '请输入产品简介' }]}
                  style={{ marginBottom: 20 }}
                >
                  <TextArea
                    maxLength={500}
                    showCount
                    style={{
                      minHeight: 100,
                      resize: 'vertical',
                    }}
                  />
                </Form.Item>
                <Form.Item
                  name="productEvaluationDesc"
                  label="产品详情"
                  rules={[{ required: true, message: '请输入产品详情' }]}
                  style={{ marginBottom: 20 }}
                >
                  <TextArea
                    maxLength={500}
                    showCount
                    style={{
                      minHeight: 100,
                      resize: 'vertical',
                    }}
                  />
                </Form.Item>
              </Form>
            </Card>

            {/* 使用场景 */}
            <Card title="使用场景" bordered>
              <Form layout="vertical" initialValues={modalState.data.usageScenario}>
                <Form.Item
                  name="industry"
                  label="所属行业"
                  rules={[{ required: true, message: '请选择所属行业' }]}
                >
                  <Select placeholder="请选择所属行业" style={{ width: '100%' }}>
                    <Select.Option value="制造业">制造业</Select.Option>
                    <Select.Option value="服务业">服务业</Select.Option>
                    <Select.Option value="金融业">金融业</Select.Option>
                    <Select.Option value="医疗健康">医疗健康</Select.Option>
                    <Select.Option value="教育行业">教育行业</Select.Option>
                  </Select>
                </Form.Item>

                <Form.Item
                  name="subIndustry"
                  label="细分行业"
                  rules={[{ required: true, message: '请选择细分行业' }]}
                >
                  <Select placeholder="请选择细分行业" style={{ width: '100%' }}>
                    <Select.Option value="汽车制造">汽车制造</Select.Option>
                    <Select.Option value="电子信息">电子信息</Select.Option>
                    <Select.Option value="物流运输">物流运输</Select.Option>
                    <Select.Option value="餐饮服务">餐饮服务</Select.Option>
                    <Select.Option value="软件开发">软件开发</Select.Option>
                  </Select>
                </Form.Item>
                <Form.List name="digitalContentList">
                  {(fields, { add, remove }) => (
                    <>
                      {fields.map(({ key, name, ...restField }) => (
                        <div
                          key={key}
                          style={{
                            marginBottom: 24,
                            borderBottom: '1px solid #e8e8e8',
                            paddingBottom: 16,
                          }}
                        >
                          <Form.Item
                            {...restField}
                            label="场景"
                            name={[name, 'scene']}
                            rules={[{ required: true, message: '请选择场景' }]}
                            style={{ marginBottom: 20 }}
                          >
                            <TreeSelect
                              allowClear
                              placeholder="请选择场景"
                              treeData={condition.map((node) => convertNode(node))}
                              treeDefaultExpandAll
                              showSearch
                              disabled
                            />
                          </Form.Item>

                          <Form.Item
                            {...restField}
                            label="场景描述"
                            name={[name, 'sceneDesc']}
                            rules={[{ required: true, message: '请输入场景描述' }]}
                            style={{ marginBottom: 20 }}
                          >
                            <TextArea
                              placeholder="请输入场景描述"
                              allowClear
                              showCount
                              maxLength={500}
                              style={{
                                minHeight: 120,
                                maxHeight: 200,
                                resize: 'vertical',
                              }}
                            />
                          </Form.Item>
                        </div>
                      ))}
                    </>
                  )}
                </Form.List>
              </Form>
            </Card>
          </Space>
        );

      case 'reg':
        return (
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            {/* 企业基本信息 */}
            <Card title="企业基本信息" bordered>
              <Form layout="vertical" initialValues={modalState.data.enterpriseInfo}>
                <Form.Item name="enterpriseName" label="企业名称">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="unifiedSocialCreditCode" label="统一社会信用代码">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="legalRepresentative" label="法定代表人">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="establishmentDate" label="成立日期">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="registeredCapital" label="注册资本">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="enterpriseType" label="企业类型">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="industry" label="所属行业">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="businessScope" label="经营范围">
                  <TextArea rows={3} allowClear />
                </Form.Item>
              </Form>
            </Card>

            {/* 联系方式 */}
            <Card title="联系方式" bordered>
              <Form layout="vertical" initialValues={modalState.data.contactInfo}>
                <Form.Item name="contactPerson" label="联系人">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="contactPhone" label="联系电话">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="contactEmail" label="电子邮箱">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="contactAddress" label="联系地址">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="postalCode" label="邮政编码">
                  <Input allowClear />
                </Form.Item>
              </Form>
            </Card>

            {/* 资质信息 */}
            <Card title="资质信息" bordered>
              <Form layout="vertical" initialValues={modalState.data.qualificationInfo}>
                <Form.Item name="hasISO" label="是否通过ISO认证">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="isoCertNumber" label="ISO证书编号">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="hasPatent" label="是否拥有专利">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="patentCount" label="专利数量">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="hasHonor" label="是否获得荣誉资质">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="honorDetails" label="荣誉资质详情">
                  <TextArea rows={3} allowClear />
                </Form.Item>
              </Form>
            </Card>
          </Space>
        );

      case 'record':
        return (
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            {/* 数字化改造需求 */}
            <Card title="数字化改造需求" bordered>
              <Form layout="vertical" initialValues={modalState.data.digitalTransformationNeeds}>
                <Form.Item name="enterpriseName" label="企业名称">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="projectName" label="项目名称">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="projectCycle" label="项目周期">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="totalInvestment" label="项目总投资（万元）">
                  <InputNumber style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item name="investmentSource" label="资金来源">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="mainProblems" label="企业面临的主要问题">
                  <TextArea rows={3} allowClear />
                </Form.Item>
                <Form.Item name="transformationGoals" label="数字化改造目标">
                  <TextArea rows={3} allowClear />
                </Form.Item>
                <Form.Item name="expectedEffects" label="预期效果">
                  <TextArea rows={3} allowClear />
                </Form.Item>
                <Form.Item name="plannedProducts" label="计划使用的产品和解决方案">
                  <TextArea rows={2} allowClear />
                </Form.Item>
              </Form>
            </Card>

            {/* 数字化改造情况 */}
            <Card title="数字化改造情况" bordered>
              <Form layout="vertical" initialValues={modalState.data.digitalTransformationStatus}>
                <Form.Item name="startDate" label="项目启动日期">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="progress" label="当前进度">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="completedContent" label="已完成内容">
                  <TextArea rows={3} allowClear />
                </Form.Item>
                <Form.Item name="ongoingContent" label="进行中内容">
                  <TextArea rows={3} allowClear />
                </Form.Item>
                <Form.Item name="problems" label="遇到的问题">
                  <TextArea rows={2} allowClear />
                </Form.Item>
                <Form.Item name="nextPlan" label="下一步计划">
                  <TextArea rows={2} allowClear />
                </Form.Item>
                <Form.Item name="actualEffects" label="已产生的实际效果">
                  <TextArea rows={2} allowClear />
                </Form.Item>
              </Form>
            </Card>
          </Space>
        );

      case 'acceptance':
        return (
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            {/* 基本信息 */}
            <Card title="基本信息" bordered>
              <Form layout="vertical" initialValues={modalState.data.basicInfo}>
                <Form.Item name="enterpriseName" label="企业名称">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="projectName" label="项目名称">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="projectCode" label="项目编号">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="startDate" label="项目启动日期">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="completionDate" label="项目完成日期">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="actualInvestment" label="实际投资额（万元）">
                  <InputNumber style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item name="declaredSubsidy" label="申报奖补金额（万元）">
                  <InputNumber style={{ width: '100%' }} />
                </Form.Item>
              </Form>
            </Card>

            {/* 完成情况 */}
            <Card title="完成情况" bordered>
              <Form layout="vertical" initialValues={modalState.data.completionStatus}>
                <Form.Item name="completionRate" label="任务完成率">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="mainTasks" label="主要任务完成情况">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="projectEffects" label="项目成效">
                  <TextArea rows={4} allowClear />
                </Form.Item>
                <Form.Item name="digitalLevel" label="数字化水平等级">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="evaluationReport" label="自我评价报告">
                  <TextArea rows={3} allowClear />
                </Form.Item>
              </Form>
            </Card>

            {/* 佐证材料 */}
            <Card title="佐证材料" bordered>
              <Form layout="vertical" initialValues={modalState.data.supportingMaterials}>
                <Form.Item name="hasFinalReport" label="是否提供项目总结报告">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="hasAuditReport" label="是否提供审计报告">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="hasPerformanceData" label="是否提供绩效数据">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="hasBeforeAfterComparison" label="是否提供改造前后对比材料">
                  <Input allowClear />
                </Form.Item>
                <Form.Item name="otherMaterials" label="其他材料">
                  <TextArea rows={2} allowClear />
                </Form.Item>
              </Form>
            </Card>
          </Space>
        );

      default:
        return null;
    }
  };

  const searchFunction = (values: any) => {
    page({
      ...values,
      loginInArea: initialState?.currentUser.data.loginInArea,
      userType: initialState?.currentUser.data.userType,
      auditStatus: "待%审核"
    }).then(res => {
      const { code, data } = res;
      if (code == 0) {
        // //message.success("查询成功")
        setProductList(data.records || [])
        setPagination({
          current: data.current,
          pageSize: data.size,
          total: data.total
        })
      }
    })
  }

  const searchUsers = (values: any) => {
    pageUsers({
      ...values,
      loginInArea: initialState?.currentUser.data.loginInArea,
      userType: initialState?.currentUser.data.userType,
      auditStatus: "待%审核"
    }).then(res => {
      const { code, data } = res
      if (code == "0") {
        setEnterpriseRegList(data.records)
        setComPagination({
          current: data.current,
          pageSize: data.size,
          total: data.total
        })
        // //message.success("请求成功")
      }
    })
  }

  const searchProgramCheck = (values: any) => {
    getProgramRecord({
      ...values,
      loginInArea: initialState?.currentUser.data.loginInArea,
      userType: initialState?.currentUser.data.userType,
      auditStatus: "待%审核"
    }).then(res => {
      const { code, data } = res
      if (code == "0") {
        setEnterpriseAcceptanceList(data.records)
        setProgramCheckPagination({
          current: data.current,
          pageSize: data.size,
          total: data.total
        })
        // //message.success("请求成功")
      }
    })
  }

  const searchProgram = (values: any) => {
    pageRecord({
      ...values,
      loginInArea: initialState?.currentUser.data.loginInArea,
      userType: initialState?.currentUser.data.userType,
      auditStatus: "待%审核"
    }).then(res => {
      const { code, data } = res
      if (code == "0") {
        const newRecord = data.records.map((item: any) => {
          return {
            ...item,
            productSolutionNames: item.digitalContentList?.reduce((pre: any, cur: { productName: any[]; }) => pre += cur.productName.join(","), ""),
            relatedServiceProviders: item.digitalContentList?.reduce((pre: any, cur: { connectService: any[]; }) => pre += cur.connectService.join(","), ""),
            digitalContentList: item.digitalContentList?.map((itemDigital: any) => ({
              ...itemDigital,
              programEnd: dayjs(itemDigital.programEnd),
              programStart: dayjs(itemDigital.programStart)
            }))
          }
        })
        setEnterpriseRecordList(newRecord)
        setProgramPagination({
          current: data.current,
          pageSize: data.size,
          total: data.total
        })
        // //message.success("请求成功")
      }
    })
  }

  useEffect(() => {
    searchFunction({
      current: pagination.current,
      pageSize: pagination.pageSize,

    })
    searchUsers({
      current: comPagination.current,
      pageSize: comPagination.pageSize,

    })
    searchProgram({
      current: comPagination.current,
      pageSize: comPagination.pageSize,

    })
    searchProgramCheck({
      current: programCheckPagination.current,
      pageSize: programCheckPagination.pageSize
    })
  }, [])

  const searchCallProductFun = () => {
    searchFunction({ current: pagination.current, pageSize: pagination.pageSize })
  }

  const searchCallCompanyFun = () => {
    searchUsers({ current: pagination.current, pageSize: pagination.pageSize })
  }
  const searchCallProgramFun = () => {
    searchProgram({ current: comPagination.current, pageSize: comPagination.pageSize })
  }

  const searchCallProgramCheckFun = () => {
    searchProgramCheck({ current: comPagination.current, pageSize: comPagination.pageSize })
  }

  return (
    <div className="my-todo-page" style={{ padding: '20px' }}>
      <div
        style={{
          fontSize: 16,
          fontWeight: 500,
          color: '#1f2937',
          marginBottom: 12,
        }}
      >
        我的待办
      </div>

      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        style={{ marginTop: '20px' }}
        items={[
          {
            key: 'product',
            label: '产品和解决方案管理',
            children: (
              <Card
                style={{
                  // margin: '16px',
                  borderRadius: 12,
                  boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
                  // height: 'calc(100vh - 120px)', // 精确高度，保证内部滚动
                  // overflowY: 'auto', // 内部滚动
                  padding: '24px',
                }}
              >
                <div
                  style={{
                    fontSize: 16,
                    fontWeight: 500,
                    color: '#1f2937',
                    marginBottom: 12,
                  }}
                >
                  产品和解决方案管理
                </div>
                <Table
                  columns={productColumns as any}
                  dataSource={productList}
                  rowKey="id"
                  className="custom-table1"
                  pagination={{ pageSize: pagination.pageSize, current: pagination.current, total: pagination.total, showSizeChanger: true }}
                  bordered
                  scroll={{ y: 'calc(100vh - 450px)' }}
                  locale={{ emptyText: '暂无待审核产品' }}
                />
              </Card>
            ),
          },
          {
            key: 'reg',
            label: '试点企业注册管理',
            children: (
              <Card
                style={{
                  // margin: '16px',
                  borderRadius: 12,
                  boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
                  // height: 'calc(100vh - 120px)', // 精确高度，保证内部滚动
                  // overflowY: 'auto', // 内部滚动
                  padding: '24px',
                }}
              >
                <div
                  style={{
                    fontSize: 16,
                    fontWeight: 500,
                    color: '#1f2937',
                    marginBottom: 12,
                  }}
                >
                  试点企业注册管理
                </div>
                <Table
                  columns={enterpriseRegColumns as any}
                  dataSource={enterpriseRegList}
                  rowKey="id"
                  className="custom-table1"
                  pagination={{ pageSize: comPagination.pageSize, current: comPagination.current, total: comPagination.total, showSizeChanger: true }}
                  bordered
                  scroll={{ y: 'calc(100vh - 450px)' }}
                  locale={{ emptyText: '暂无待审核企业注册信息' }}
                />
              </Card>
            ),
          },
          {
            key: 'record',
            label: '项目备案管理',
            children: (
              <Card
                style={{
                  // margin: '16px',
                  borderRadius: 12,
                  boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
                  // height: 'calc(100vh - 120px)', // 精确高度，保证内部滚动
                  // overflowY: 'auto', // 内部滚动
                  padding: '24px',
                }}
              >
                <div
                  style={{
                    fontSize: 16,
                    fontWeight: 500,
                    color: '#1f2937',
                    marginBottom: 12,
                  }}
                >
                  项目备案管理
                </div>
                <Table
                  columns={enterpriseRecordColumns as any}
                  dataSource={enterpriseRecordList}
                  rowKey="id"
                  className="custom-table1"
                  pagination={{ pageSize: programPagination.pageSize, current: programPagination.current, total: programPagination.total, showSizeChanger: true }}

                  bordered
                  scroll={{ y: 'calc(100vh - 450px)' }}
                  locale={{ emptyText: '暂无待审核企业备案信息' }}
                />
              </Card>
            ),
          },
          {
            key: 'acceptance',
            label: '项目验收管理',
            children: (
              <Card
                style={{
                  // margin: '16px',
                  borderRadius: 12,
                  boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
                  // height: 'calc(100vh - 120px)', // 精确高度，保证内部滚动
                  // overflowY: 'auto', // 内部滚动
                  padding: '24px',
                }}
              >
                <div
                  style={{
                    fontSize: 16,
                    fontWeight: 500,
                    color: '#1f2937',
                    marginBottom: 12,
                  }}
                >
                  项目验收管理
                </div>
                <Table
                  columns={enterpriseAcceptanceColumns as any}
                  dataSource={enterpriseAcceptanceList}
                  rowKey="id"
                  className="custom-table1"
                  pagination={{ pageSize: programCheckPagination.pageSize, current: programCheckPagination.current, total: programCheckPagination.total, showSizeChanger: true }}

                  bordered
                  scroll={{ y: 'calc(100vh - 450px)' }}
                  locale={{ emptyText: '暂无项目验收管理信息' }}
                />
              </Card>
            ),
          },
        ].filter(item => item.label == "试点企业注册管理" && initialState?.currentUser.data.userType == "city" ? false : true).filter(item => item.label == "产品和解决方案管理" && initialState?.currentUser.data.userType == "county" ? false : true)}
      />
      <ProductAllInfosPage searchCallFun={searchCallProductFun} />
      <CompanyAllInfosPage searchCallFun={searchCallCompanyFun} />
      <RecordAllInfosPage searchCallFun={searchCallProgramFun} />
      <AcceptanceManagerPage searchCallFun={searchCallProgramCheckFun} />
      {/* 审核弹窗 */}
      <Modal
        title={
          <>
            {modalState.type === 'product' && '产品审核（测试模式）'}
            {modalState.type === 'reg' && '试点企业注册审核（测试模式）'}
            {modalState.type === 'record' && '试点企业备案审核（测试模式）'}
            {modalState.type === 'acceptance' && '试点企业验收审核（测试模式）'}
          </>
        }
        open={modalState.visible}
        onCancel={handleModalClose}
        maskClosable={false}
        destroyOnClose
        width={1000}
        footer={null}
        bodyStyle={{ maxHeight: '70vh', overflow: 'auto' }}
      >
        {renderModalContent()}

        {/* 审核意见区域 */}
        <Divider>审核意见</Divider>
        <Form form={reviewForm} layout="vertical">
          <Form.Item
            name="reviewOpinion"
            label={
              <span>
                审核意见 <span style={{ color: 'red' }}>*</span>
              </span>
            }
            rules={[{ required: true, message: '请填写审核意见' }]}
          >
            <TextArea rows={4} placeholder="请输入审核意见" />
          </Form.Item>
        </Form>

        {/* 操作按钮 */}
        <div
          style={{ display: 'flex', justifyContent: 'flex-end', gap: '16px', marginTop: '16px' }}
        >
          <Button onClick={handleModalClose}>取消</Button>
          <Button
            type="default"
            danger
            onClick={() => handleSubmitReview('reject')}
            icon={<CloseCircleOutlined />}
          >
            不通过
          </Button>
          <Button
            type="default"
            onClick={() => handleSubmitReview('return')}
            icon={<SyncOutlined spin={false} />}
          >
            退回
          </Button>
          <Button
            type="primary"
            onClick={() => handleSubmitReview('pass')}
            icon={<CheckCircleOutlined />}
          >
            通过
          </Button>
        </div>
      </Modal>
    </div>
  );
};

export default MyTodoPage;
